import React, { useEffect, useRef, useState } from 'react';
import { Layout, Modal } from 'antd';
import LeftSider from './components/LeftSider';
import RightDraw from './components/RightDraw';
import EditorArea from './components/EditorArea';
import { ArticleStatus } from "common/utils/data";
import { useMemoizedFn } from "ahooks";
import { darkThemeStorage } from "@/utils/storage";
import { useModel } from "@umijs/max";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";

export default function Article(){

  const {setCollapse} = useModel('personal.model', ({setCollapse})=>{
    return {
      setCollapse
    }
  });

  useEffect(() => {
    setCollapse(true);
  }, []);

  useEffect(() => {
    if(process.env.NODE_ENV !== 'development'){
      window.onbeforeunload = () => {
        return true;
      };
      return () => {
        window.onbeforeunload = null;
      };
    }
  },[]);

  // 是否编辑过
  const [edited,setEdited] = useState<boolean>(false);

  const unsaveCheck = useMemoizedFn(() => {
    return new Promise<void>((resolve) => {
      if (!edited){
        resolve();
        return;
      }
      Modal.confirm({
        type: 'warn',
        title: '内容未保存',
        content: '编辑内容还未保存，是否继续？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        centered: true,
        onOk() {
          resolve();
        },
      });
    });
  });

  const [activeArticleUuid, setActiveArticleUuid] = useState<string | null>(null);

  const [drawerVisible,setDrawerVisible] = useState<boolean>(false);

  // 设置激活文章前的检测函数
  const setActiveArticleUuidHandle = useMemoizedFn(async (uuid: string | null)=>{
    unsaveCheck().then(()=>{
      setActiveArticleUuid(uuid);
      setEdited(false);
    });
  });

  // 保存前处理
  const beforeSave = useMemoizedFn((status?: string)=>{
    return new Promise<void>(resolve => {
      if (status === ArticleStatus.DRAFT) {
        resolve();
        return;
      }
      Modal.confirm({
        type: 'error',
        title: '保存确认',
        content: '保存后当前文章将下架，状态将变为[草稿]',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        centered: true,
        onOk() {
          resolve();
        },
      });
    })
  });

  const [darkTheme,setDarkTheme] = useState<boolean>(()=>{
    const darkThemeStr = darkThemeStorage.get();
    return !!darkThemeStr;
  });

  useEffect(()=>{
    if(darkTheme){
      const styleLink = document.createElement('link');
      styleLink.type = 'text/css';
      styleLink.rel = 'stylesheet';
      styleLink.id = 'theme-style';
      // @ts-ignore
      styleLink.href = `${window.routerBase}theme/dark.css`;
      document.head.append(styleLink);
      document.body.className = 'body-wrap-dark';
      darkThemeStorage.set('1');
    }else{
      const styleLink = document.querySelector<HTMLLinkElement>('#theme-style');
      styleLink?.remove();
      document.body.className = 'body-wrap-light';
      darkThemeStorage.remove();
    }
  },[darkTheme])

  const refreshList = useRef<()=>void>();

  const refreshEditor = useRef<()=>void>();

  return (
    <>
      <PanelGroup autoSaveId="personal-article" direction="horizontal">
        <Panel defaultSize={25} style={{
          minWidth: 400,
        }}>
          <LeftSider
            setDrawerVisible={setDrawerVisible}
            activeArticleUuid={activeArticleUuid}
            setActiveArticleUuid={setActiveArticleUuidHandle}
            darkTheme={darkTheme}
            setDarkTheme={setDarkTheme}
            refreshList={refreshList}
          />
        </Panel>
        <PanelResizeHandle style={{width: 8}} />
        <Panel style={{
          minWidth: 800,
        }}>
          <EditorArea
            setDrawerVisible={setDrawerVisible}
            activeArticleUuid={activeArticleUuid}
            setActiveArticleUuid={setActiveArticleUuidHandle}
            setEdited={setEdited}
            edited={edited}
            beforeSave={beforeSave}
            refreshEditor={refreshEditor}
            refreshList={refreshList}
          />
        </Panel>
      </PanelGroup>
      <RightDraw
        drawerVisible={drawerVisible}
        setDrawerVisible={setDrawerVisible}
        activeArticleUuid={activeArticleUuid}
        setActiveArticleUuid={setActiveArticleUuidHandle}
        refreshEditor={refreshEditor}
        refreshList={refreshList}
        beforeSave={beforeSave}
      />
    </>

  );
};
